<template>
  <el-card>
    <el-button type="primary" @click="openAddDialog">新增心情记录</el-button>
    <el-table :data="moodList" style="width: 100%; margin-top: 20px;">
      <el-table-column prop="moodId" label="记录ID" width="80" />
      <el-table-column prop="userId" label="用户ID" />
      <el-table-column prop="mood" label="心情" />
      <el-table-column prop="content" label="日记内容" />
      <el-table-column prop="moodDate" label="记录日期" />
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="small" @click="openEditDialog(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteMood(scope.row.moodId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="dialogTitle" v-model="dialogVisible">
      <el-form :model="form">
        <el-form-item label="用户ID">
          <el-input v-model="form.userId" />
        </el-form-item>
        <el-form-item label="心情">
          <el-input v-model="form.mood" />
        </el-form-item>
        <el-form-item label="日记内容">
          <el-input type="textarea" v-model="form.content" />
        </el-form-item>
        <el-form-item label="记录日期">
          <el-date-picker v-model="form.moodDate" type="date" placeholder="选择日期" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { getMoodDiariesByUserId, addMoodDiary, updateMoodDiary, deleteMoodDiary } from '@/api/mood';
import { ElMessageBox } from 'element-plus';

const moodList = ref([]);
const dialogVisible = ref(false);
const dialogTitle = ref('新增心情记录');
const form = ref({ moodId: null, userId: '', mood: '', content: '', moodDate: '' });
let isEdit = false;

const loadMood = async () => {
  moodList.value = await getMoodDiariesByUserId(1);
};

const openAddDialog = () => {
  isEdit = false;
  dialogTitle.value = '新增心情记录';
  form.value = { moodId: null, userId: '', mood: '', content: '', moodDate: '' };
  dialogVisible.value = true;
};

const openEditDialog = (record) => {
  isEdit = true;
  dialogTitle.value = '编辑心情记录';
  form.value = { ...record };
  dialogVisible.value = true;
};

const submitForm = async () => {
  if (isEdit) {
    await updateMoodDiary(form.value);
  } else {
    await addMoodDiary(form.value);
  }
  dialogVisible.value = false;
  loadMood();
};

const deleteMood = async (moodId) => {
  await ElMessageBox.confirm('确定删除该记录吗?', '提示', { type: 'warning' });
  await deleteMoodDiary(moodId);
  loadMood();
};

onMounted(() => {
  loadMood();
});
</script>
